package com.xsf.pay.common.resolver;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xsf.pay.common.domain.Result;
import com.xsf.pay.common.domain.ResultData;
import com.xsf.pay.common.utils.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * 自动转换类
 *
 * @author 呆毛一哥
 */
@Component
@ControllerAdvice
@Slf4j
public class ConvertResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("====开始消息转换处理====");
        try {
            if (body instanceof Result) {
                Object data = ((Result<?>) body).getData();
                if (ObjectUtil.isNull(data)) {
                    return body;
                }
                if (data instanceof List<?>) {
                    ConvertUtils.fieldValSetList((List<?>) ((Result<?>) body).getData());
                } else if (data instanceof IPage<?>) {
                    ConvertUtils.fieldValSetList(((IPage<?>) ((Result<?>) body).getData()).getRecords());
                } else {
                    ConvertUtils.fieldValSet(((Result<?>) body).getData());
                }
            }
            if (body instanceof ResultData<?>) {
                Object data = ((ResultData<?>) body).getData();
                if (ObjectUtil.isNull(data)) {
                    return body;
                }
                if (data instanceof List<?>) {
                    ConvertUtils.fieldValSetList((List<?>) ((ResultData<?>) body).getData());
                } else if (data instanceof IPage<?>) {
                    ConvertUtils.fieldValSetList(((IPage<?>) ((ResultData<?>) body).getData()).getRecords());
                } else {
                    ConvertUtils.fieldValSet(((ResultData<?>) body).getData());
                }
            }
        } catch (Exception e) {
            log.info("执行消息转换错误");
        }
        return body;
    }
}
